'''
-*- coding: utf-8 -*-
@File  : mypoe.py
@Author: Shanmh
@Time  : 2024/01/26 下午5:42
@Function：
'''
import json
import os
import sys
import time
import re
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from fake_useragent import UserAgent
Keys=webdriver.common.keys.Keys()
By=webdriver.common.by.By()

current=os.path.dirname(os.path.abspath(__file__))

class MyPoe():


    _instance = None

    def __new__(cls, *args, **kwargs):
        if not cls._instance:
            cls._instance = super().__new__(cls, *args, **kwargs)
        return cls._instance
    def init(self):
        # 创建 UserAgent 对象
        user_agent = UserAgent()

        # 生成随机的 User-Agent 字符串
        random_user_agent = user_agent.random

        # 创建 Chrome WebDriver 的选项对象
        chrome_options = Options()

        # 设置 User-Agent
        chrome_options.add_argument(f'user-agent={random_user_agent}')

        self.br=webdriver.Chrome(options=chrome_options)

        self.input_e=None
        self.enter_e=None
        self.stop_e=None

    def start_poe(self):
        self.br.get("https://poe.com")


        #加载cookies，刷新br
        listCookies=[]
        with open(f'{current}/poe_cookies.json', 'r', encoding='utf8') as f:
            listCookies = json.loads(f.read())
            f.close()

        # 先清除所有cookies
        self.br.delete_all_cookies()

        for cookies in listCookies:
            cmd = f"document.cookie = \'{cookies['name']}={cookies['value']}\'"
            self.br.execute_script(cmd)

        self.br.refresh()



    def get_text(self):
        # 查找所有的textarea元素
        textareas = self.br.find_elements("css selector", "textarea")
        input_e = None
        # 遍历每个textarea元素
        for textarea in textareas:
            # 获取placeholder属性值
            placeholder = textarea.get_attribute("placeholder")
            # 筛选出placeholder为"hello"的元素
            if placeholder == "与Assistant交谈" or placeholder == "开始新的聊天":
                input_e = textarea
                break
        return input_e

    def get_send(self):
        send_e = None
        path_d = "M4 13h14.09l-6.79 6.79a.996.996 0 1 0 1.41 1.41l8.5-8.5c.06-.06.09-.13.13-.2.03-.04.06-.08.08-.13a.91.91 0 0 0 .08-.37c0-.03-.01-.05-.01-.07-.01-.1-.02-.21-.06-.31a.955.955 0 0 0-.22-.33L12.72 2.8c-.2-.2-.45-.29-.71-.29-.26 0-.51.1-.71.29a.996.996 0 0 0 0 1.41L18.08 11H4c-.55 0-1 .45-1 1s.45 1 1 1Z"

        # 查找所有的button元素
        path_es = self.br.find_elements("css selector", "path")
        send_e = None
        # 遍历每个path_es元素
        for path_e in path_es:
            # 获取d属性值
            d = path_e.get_attribute("d")
            # 筛选出placeholder为"hello"的元素
            if d == path_d:
                send_e = path_e

        # 获取元素的父节点元素
        parent_element1 = send_e.find_element(By.XPATH, "..")
        # 获取元素的父节点元素
        parent_element2 = parent_element1.find_element(By.XPATH, "..")
        return parent_element2

    def get_context(self):
        good_d = "M10.286 3.594A1 1 0 0 1 11.2 3a3.4 3.4 0 0 1 3.4 3.4v2.2h3.523a2.6 2.6 0 0 1 2.594 2.99l-1.104 7.2A2.601 2.601 0 0 1 17.019 21H5.6A2.6 2.6 0 0 1 3 18.4v-5.6a2.6 2.6 0 0 1 2.6-2.6h1.75l2.936-6.606ZM7 12.2H5.6a.6.6 0 0 0-.6.6v5.6a.6.6 0 0 0 .6.6H7v-6.8ZM9 19v-7.588l2.792-6.281A1.4 1.4 0 0 1 12.6 6.4v3.2a1 1 0 0 0 1 1h4.539a.6.6 0 0 1 .6.69c0-.001 0 0 0 0l-1.104 7.2a.6.6 0 0 1-.6.51H9Z"
        good_e = None
        # 查找所有的button元素
        path_es = self.br.find_elements("css selector", "path")
        send_e = None
        # 遍历每个path_es元素
        for path_e in path_es:
            # 获取d属性值
            d = path_e.get_attribute("d")
            # 筛选出placeholder为"hello"的元素
            if d == good_d:
                good_e = path_e

        # 获取元素的父节点元素
        parent_element1 = good_e.find_element(By.XPATH, "../../../..")
        #print(parent_element1.get_attribute("class"))

        childends = parent_element1.find_elements(By.XPATH, "./div")

        return childends


    def send(self,message):
        n=10
        flag=True
        while n and  flag:
            try:
                self.input_e.clear()
                self.input_e.send_keys(f"{message} 50字以内回复")
                self.enter_e.click()
                flag=False
                return True
            except:
                print("发送信息出现了错误")
                self.input_e=self.get_text()
                self.enter_e=self.get_send()
                n-=1
                pass
        return False

    def receive(self):
        n = 30
        flag = True
        context_e=None
        while n and flag:
            try:
                context_e = self.get_context()
                flag = False
                return context_e[1].text
            except:
                print("接受信息出现了错误")
                time.sleep(1)
                n -= 1
                pass
        return "AI Bot is amazing ！！！ please wait patiently."



if __name__ == '__main__':
    poe=MyPoe()
    poe.init()
    poe.start_poe()
    poe.send("你好呀")
    time.sleep(1)
    reply=poe.receive()
    print(reply)








